/*
 * 项目名称:keel-flower
 * 类名称:R.java
 * 包名称:me.keelflower.utils
 *
 * 修改履历:
 *      日期                修正者      主要内容
 *      2020/11/28 22:55    liliudong      初版完成
 *
 */
package com.liliudong.pinkyponk.core.util;

import com.alibaba.fastjson2.JSONObject;
import com.liliudong.pinkyponk.core.constant.ResponseMessage;
import lombok.Getter;
import org.springframework.http.ResponseEntity;

/**
 * 全局返回类
 *
 * @author liliudong 2020/11/28 22:55
 */
@Getter
public class R<M> {

    private final String msg;
    private final int code;
    private M data;

    private R(ResponseMessage responseMessage, M data) {
        this.data = data;
        this.code = responseMessage.code;
        this.msg = responseMessage.message;
    }

    public static <T> ResponseEntity<R<T>> ok(T t) {
        R<T> r = new R<>(ResponseMessage.OK, t);
        return ResponseEntity.ok(r);
    }

    public static ResponseEntity<R<Object>> ok() {
        return ok(null);
    }

    public static ResponseEntity<R<?>> error(ResponseMessage responseMessage) {
        R<?> r = new R<>(responseMessage, null);
        return ResponseEntity.ok(r);
    }

    public static ResponseEntity<R<?>> error() {
        return error(ResponseMessage.ERROR);
    }

    public static R<JSONObject> of() {
        return new R<>(ResponseMessage.OK, new JSONObject());
    }

    public R<?> put(String key, Object value) {
        if (this.data instanceof JSONObject) {
            JSONObject data = (JSONObject) this.data;
            data.put(key, value);
        }
        return this;
    }

    public ResponseEntity<?> get() {
        return ok(this.data);
    }
}
